package home

import (
	"dustbe/database"
	"encoding/json"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"

	"dustbe/controller/slidev"
)

type ServerInfo struct {
	MemUsedPercent float64 `json:"memUsage"`
	DiskUsage      float64 `json:"diskUsage"`
	CpuUsage       float64 `json:"cpuUsage"`
}

func GetServerInfo(c *gin.Context) {
	cpuUsages, _ := cpu.Percent(time.Second, false)
	cpuUsage := cpuUsages[0]
	mem, _ := mem.VirtualMemory()
	disk, _ := disk.Usage(countDisk)
	memUsage := mem.UsedPercent
	diskUsage := disk.UsedPercent

	basicInfo := ServerInfo{
		MemUsedPercent: memUsage,
		DiskUsage:      diskUsage,
		CpuUsage:       cpuUsage,
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": basicInfo})
}

type NewsThing struct {
	Blogs   []map[string]interface{} `json:"blogs"`
	Slidevs []slidev.SlidevMetaItem  `json:"slidevs"`
}

// 获取最新的文章、博客之类的
func GetNews(c *gin.Context) {
	nodes, err := database.GetBlogByPage(1, 3)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "查询最新博客失败"})
		return
	}

	// 获取最新的slidev

	file, err := os.Open(slidev.SlidevIndexPath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "本地文件打开错误"})
		return
	}

	defer file.Close()
	decoder := json.NewDecoder(file)

	var slidevMeta slidev.SlidevMeta
	err = decoder.Decode(&slidevMeta)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "本地meta json解析失败"})
		return
	}

	newsThing := NewsThing{
		Blogs:   nodes,
		Slidevs: slidevMeta.Content[:3],
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": newsThing})
}
